package com.leen.service;

import com.alibaba.fastjson.JSONObject;
import com.leen.common.util.StringUtils;
import com.leen.config.QiniuProperties;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.Region;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;
import net.coobird.thumbnailator.Thumbnails;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.unit.DataSize;
import org.springframework.web.multipart.MultipartFile;

import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * 类说明
 *
 * @author admin
 * @date 2021-04-14
 */
@Service
public class QiniuService {

    @Autowired
    private QiniuProperties qiniuProperties;

    public DefaultPutRet uploadFile(MultipartFile file) throws IOException {
        //构造一个带指定 Region 对象的配置类
        Configuration cfg = new Configuration(Region.huanan());
        //...其他参数参考类注释
        UploadManager uploadManager = new UploadManager(cfg);
        //...生成上传凭证，然后准备上传
        String accessKey =this.qiniuProperties.getAccessKey();
        String secretKey =this.qiniuProperties.getSecretKey();
        String bucket = this.qiniuProperties.getBucket();
        //登录
        Auth auth = Auth.create(accessKey, secretKey);
        String upToken = auth.uploadToken(bucket);

        String localFilePath=file.getOriginalFilename();

        //取得文件后缀   d:\\11.jpg
        int index=localFilePath.lastIndexOf(".");
        // .jpg
        String ext=localFilePath.substring(index);
        //图片输出格式   jpg
        String outputFormat=localFilePath.substring(index+1).toLowerCase();
        //重命名
        String uuid= UUID.randomUUID().toString().replaceAll("-","");
        String key = uuid+ext;


        //做一个大小判断
        DataSize dataSize = DataSize.parse(this.qiniuProperties.getImageSize());
        long  dataSizeByte=dataSize.toBytes();
        //拿这个字节与 上传文件字节来比较
        long fileSize=file.getSize();

        Response response=null;
        //超过我的大小,压缩，放到内存中去
        ByteArrayOutputStream baos=new ByteArrayOutputStream();
        if(fileSize > dataSizeByte){
            //把图片 放到内存中
            Thumbnails.of(file.getInputStream())
                    .imageType(BufferedImage.TYPE_INT_ARGB)
                    .scale(1.0f)
                    .outputQuality(0.5f)
                    .outputFormat(outputFormat)
                    .toOutputStream(baos);

            //压缩后的文件上传
            response = uploadManager.put(baos.toByteArray(), key, upToken);
        }else{
            //标准文件上传
            response = uploadManager.put(file.getBytes(), key, upToken);
        }

        //解析上传成功的结果
        DefaultPutRet putRet = JSONObject.parseObject(response.bodyString(), DefaultPutRet.class);

        return putRet;
    }


    /**
     * 上传图片 ，并且生成缩略片
     * @param file
     * @return
     * @throws IOException
     */
    public Map<String,String> uploadThumbFile(MultipartFile  file) throws IOException {

        Map<String,String>  mp=new HashMap<>();

        //上传原图
        DefaultPutRet defaultPutRetOld = this.uploadFile(file);
        mp.put("original",defaultPutRetOld.key);

        //再接着上传缩略图
        int width=150;
        int height=150;
        if(this.qiniuProperties.getThumb()!=null){
            width=this.qiniuProperties.getThumb().getWidth().intValue();
            height=this.qiniuProperties.getThumb().getHeight().intValue();
        }
        DefaultPutRet putRetThumb=this.uploadQiniuThumbFile(file, defaultPutRetOld.key, width,height);
        mp.put("thumb",putRetThumb.key);

        return mp;
    }

    public DefaultPutRet uploadQiniuThumbFile(MultipartFile  file,String original,int width,int height) throws IOException {
        //构造一个带指定 Region 对象的配置类
        Configuration cfg = new Configuration(Region.huanan());
        //...其他参数参考类注释
        UploadManager uploadManager = new UploadManager(cfg);
        //...生成上传凭证，然后准备上传
        String accessKey =this.qiniuProperties.getAccessKey();
        String secretKey =this.qiniuProperties.getSecretKey();
        String bucket = this.qiniuProperties.getBucket();
        //登录
        Auth auth = Auth.create(accessKey, secretKey);
        String upToken = auth.uploadToken(bucket);

        String localFilePath=file.getOriginalFilename();

        //取得文件后缀   d:\\11.jpg
        int index=localFilePath.lastIndexOf(".");
        // .jpg
        String ext=localFilePath.substring(index);
        //图片输出格式   jpg
        String outputFormat=localFilePath.substring(index+1).toLowerCase();
        //重命名 5ddf1df9-dd21-4900-888a-37aaa629777c.jpg
        String fileName=original.substring(0,index);
        //5ddf1df9-dd21-4900-888a-37aaa629777c_150*150.jpg

        String key = StringUtils.format("{}_{}*{}.{}",fileName,width,height,outputFormat);

        Response response=null;
        //超过我的大小,压缩，放到内存中去
        ByteArrayOutputStream baos=new ByteArrayOutputStream();

        //把图片 放到内存中
        Thumbnails.of(file.getInputStream())
                .imageType(BufferedImage.TYPE_INT_ARGB)
                .size(width,height)
                .outputQuality(1.0f)
                .outputFormat(outputFormat)
                .toOutputStream(baos);

        //压缩后的文件上传
        response = uploadManager.put(baos.toByteArray(), key, upToken);


        //解析上传成功的结果
        DefaultPutRet putRet = JSONObject.parseObject(response.bodyString(), DefaultPutRet.class);

        return putRet;
    }

}
